<template>
  <div class="main_spac1">
    <div class="main_white padding10">
      <div class="mainor_form batch-wrap small-top">
        <div class="mainor_te mainsa_te">
          <!-- class="mainor_tea" -->
          <!-- <el-button @click="printAll">{{
            userCheckList.length == 0 ? "打印全部拣货单" : "批量打印拣货单"
          }}</el-button> -->
          

          <!-- <el-tooltip
            class="item marginLeft5"
            effect="dark"
            content="此功能只会影响在分拣时是否打印标签"
            placement="bottom-end"
          >
            <svg aria-hidden="true" class="navbar_svg" width="14" height="14">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip> -->
        </div>
        <div class="mainor_te on">
          <!-- <el-button v-repeatClick>一键打印</el-button> -->
          <!-- <el-button v-repeatClick>批量打印拣货单</el-button> -->
          <!-- <el-button v-repeatClick>打印所有拣货单</el-button> -->
        </div>

        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="90px"
          id="form"
        >
          <el-form-item label="配送日期：" prop="send_time">
            <el-date-picker
              v-model="form.send_time"
              type="date"
              class="wid220"
              :editable="false"
              placeholder="选择配送日期"
              value-format="yyyy-MM-dd"
              :clearable="false"
              @change="getList"
            />
          </el-form-item>

          <el-form-item label="配送时间：" prop="send_time_id">
            <el-select
              v-model.trim="form.send_time_id"
              placeholder="配送时间"
              class="wid220"
              @change="getList"
            >
              <el-option label="所有" :value="parseInt(0)"></el-option>
              <el-option
                v-for="(send_time_list, index) in searchFormData.send_time_list"
                :key="index"
                :label="send_time_list"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="配送路线：" prop="line_id">
            <el-select
              v-model.trim="form.line_id"
              placeholder="区域"
              class="wid220"
              filterable
              @change="getArticleList"
            >
              <el-option label="所有" :value="parseInt(0)"></el-option>
              <el-option
                v-for="(region, index) in searchFormData.line"
                :key="index"
                :label="region"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
          </MainFormBtn>
          <div class="more el-form-item" @click="moredata = !moredata">
            <span>更多</span>
            <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
          </div>
          <el-collapse-transition>
            <div v-show="moredata">
              <el-form-item label="用户：" prop="uid">
                <change-user-input
                  ref="changeUserInput"
                  @sendValue="getUser"
                  @clear="clearUid"
                  @zidname="uidName"
                  :getFunction="2"
                  :time="form.send_time"
                  :triggerOnFocus="true"
                ></change-user-input>
              </el-form-item>
              <el-form-item label="子账号：" prop="zid">
                <el-select
                  v-model="form.zid"
                  placeholder="子账号"
                  class="wid220"
                  no-data-text
                  filterable
                  @change="getArticleList"
                >
                  <el-option
                    v-for="(zid_time, index) in zid_name"
                    :key="index"
                    :label="zid_time.nickname"
                    :value="zid_time.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="分拣状态：" prop="sortinguser">
                <el-select
                  v-model.trim="form.sortinguser"
                  placeholder="分拣状态"
                  class="wid220"
                  @change="getArticleList"
                >
                  <el-option label="所有" :value="parseInt(0)"></el-option>
                  <el-option
                    v-for="(send_time_list, index) in searchFormData.sortingUserList"
                    :key="index"
                    :label="send_time_list"
                    :value="parseInt(index + 1)"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="用户分组：" prop="group_id">
                <el-select
                  v-model.trim="form.group_id"
                  placeholder="分组"
                  class="wid220"
                  filterable
                  @change="getArticleList"
                >
                  <el-option label="所有" :value="parseInt(0)"></el-option>
                  <el-option
                    v-for="(group, index) in searchFormData.group"
                    :key="index"
                    :label="group"
                    :value="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item label="用户区域：" prop="region_id">
                <el-select
                  v-model.trim="form.region_id"
                  placeholder="区域"
                  class="wid220"
                  filterable
                  @change="getArticleList"
                >
                  <el-option label="所有" :value="parseInt(0)"></el-option>
                  <el-option
                    v-for="(region, index) in searchFormData.region"
                    :key="index"
                    :label="region"
                    :value="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item label=" ">
                <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                </MainFormBtn>
              </el-form-item>
            </div>
          </el-collapse-transition>
        </el-form>
       
      </div>

      <div class="main-controls-wrap mg-b-4">
        <div>
          <el-button @click="selectAll">{{ isAllSelected ? "取消全选" : "全选" }}</el-button>
          <el-button @click="batchprint">批量打印</el-button>
        </div>
        <div class="batch-wrap-right">
          <!-- 分拣报表 -->
          <el-checkbox
            v-model="form.sort_rule"
            true-label="1"
            false-label="2"
            @change="changeSortRule"
            >按商品排序</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">注释：1.（勾选）按商品spuiid等排序； 2.（不勾选）是按订单内商品排序进行排序</div>
            <svg aria-hidden="true" class="navbar_svg mg-r-10" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
          <el-checkbox
            v-model="not_display_direct_supply_goods"
            @change="
              (val) => {
                checkboxChange(val, 5);
              }
            "
            >不显示直供商品</el-checkbox
          >
          <el-checkbox
            v-model="automatic_printing"
            @change="
              (val) => {
                checkboxChange(val, 1);
              }
            "
            >自动打印</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">
              注释：在使用智能称或手动输入数量并敲回车键完成分拣后，标签自动打印
            </div>
            <svg aria-hidden="true" class="navbar_svg mg-r-10" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
          <el-checkbox
            v-model="no_sorting_printing"
            @change="
              (val) => {
                checkboxChange(val, 2);
              }
            "
            >未分拣打印</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">注释：勾选后，未分拣商品也可打印</div>
            <svg aria-hidden="true" class="navbar_svg mg-r-10" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="light"
            content="表头设置"
            placement="bottom"
          >
            <svg
              @click="dialogFormVisible = true"
              aria-hidden="true"
              width="16"
              height="16"
              class="navbar_svg header_setting"
            >
              <use xlink:href="#icon-header_setting" />
            </svg>
          </el-tooltip>
            <!-- <el-checkbox
              v-model="temporary_coding"
              @change="
                (val) => {
                  checkboxChange(val, 3);
                }
              "
              >临时编码</el-checkbox
            > -->
            <!-- <el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">
                注释：勾选后，系统会按照用户的下单顺序，以数字1递增的方式，给用户自动生成一个临时数字编码
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip> -->
            <!-- <el-checkbox
              v-model="display_direct_delivery"
              @change="
                (val) => {
                  checkboxChange(val, 4);
                }
              "
              >显示直达</el-checkbox
            >
            <el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">
                注释：勾选后，供应商直送的商品会显示在列表，不可分拣或撤销分拣等
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip> -->
        </div>
      </div>

      <div
        class="table"
        v-loading="listLoading"
        :style="{ minHeight: borderHeights + 'px' }"
      >
        <div
          class="mainsw_tax table-item mg-t-10"
          v-for="(item, boxindex) in tableList"
          :key="boxindex"
        >
          <div class="main_num boxdq batch-wrap mg-b-10">
            <div class="main_num_l box">
              <p>
                <el-checkbox
                  :value="isItemSelected(item)"
                  @change="(val) => userSelectionChange(val, item)"
                ></el-checkbox>
              </p>

              <div style="display: flex; align-items: center">
                <el-popover
                  placement="bottom-start"
                  width="200"
                  trigger="hover"
                >
                  <div class="item-label">
                    <span v-for="citem in item.labels" :key="citem">
                      {{ labels[citem] }}
                    </span>
                  </div>
                  <div
                    class="user-label"
                    v-show="item.labels.length > 0"
                    slot="reference"
                  >
                    <img class="label-pic" src="../../assets/images/10.png" />
                  </div>
                </el-popover>
              </div>

              <p>
                用户名称：<em>{{ item.nickname }}</em>
              </p>
              <p>
                用户编码：<em>{{ item.formal_code }}</em>
              </p>
              <p>
                临时用户编码：<em>{{ item.cdoe }}</em>
              </p>
              <p>
                收货人：<em>{{ item.name }}</em>
              </p>

              <p>
                联系方式：<em>{{ item.mobile }}</em>
              </p>
              <p>
                收货地址：<em>{{ item.address }}</em>
              </p>
              <p>
                配送路线：<em>{{ lineType(item.line_id) }}</em>
              </p>
              <!-- <p style="margin-left: 15px; color: #03a98e">
                <router-link :to="'/order/list/see/' + item.list[0].oid">
                  更多<i class="el-icon-arrow-right"></i>
                </router-link>
              </p> -->
            </div>
            <div>
              <el-button type="primary" v-repeatClick @click="print(item)">打印拣货单</el-button>
            </div>
          </div>
          <div class="main_table">
            <el-table
              ref="multipleTable"
              :data="tableList[boxindex].is_expand ? tableList[boxindex].list : []"
              fit
              border
              highlight-current-row
              :row-class-name="boxindex == userRow.boxindex ? cellStyle : ''"
              :header-cell-style="tableHeightStyle"
              empty-text=""
              v-loading="tableList[boxindex].loading"
            >
              <div slot="empty"></div>
              <el-table-column
                label="序号"
                fixed
                type="index"
                width="80"
              >
                <template #header>
                  <div class="expand-box" @click="expandChange(boxindex)" style="cursor: pointer">
                    <i :class="tableList[boxindex].is_expand ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
                    <span>序号</span>
                  </div>
                </template>
              </el-table-column>
              <div v-for="(field, index) in field" :key="index">
                <el-table-column
                  label="商品名称"
                  width="160"
                  :show-overflow-tooltip="true"
                  v-if="field == 1"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span
                      style="color: #03a98e"
                      v-show="scope.row.purchase_mode == 3"
                      >【直】</span
                    >
                    <span
                      v-show="scope.row.out_status == 1"
                      style="color: #e6a23c"
                      >【缺】</span
                    >
                    <span
                      v-show="scope.row.modify == 1"
                      style="color: red"
                      >【更】</span
                    >
                    {{ scope.row.name }}【{{ scope.row.spu_name }}】
                  </template>
                </el-table-column>

                <el-table-column
                  label="下单数量"
                  width="120"
                  prop="order_num"
                  :show-overflow-tooltip="true"
                  v-if="field == 2"
                >
                  <template slot-scope="{ row }">
                    {{ row.base_order_num ? row.base_order_num : row.order_num+' '+row.spu_name }}
                  </template>
                </el-table-column>
                <el-table-column label="分拣数量" width="180" v-if="field == 3">
                  <template slot-scope="scope">
                    <el-input
                      :ref="'sorting' + boxindex + scope.$index"
                      v-model="scope.row.sort_num"
                      :disabled="scope.row.disabled"
                      placeholder=""
                      class="wid80"
                      size="mini"
                      @focus="inputFocus(boxindex, scope, $event)"
                      @blur="inputBlur(boxindex, scope, $event)"
                      @keyup.enter.native="nextFocus(boxindex, scope, $event, 0)"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="分拣单位" width="120" v-if="field == 4">
                  <template slot-scope="props">
                    {{ props.row.unit }}
                  </template>
                </el-table-column>
                <el-table-column label="生产日期" width="180" v-if="field == 5">
                  <template slot-scope="props">
                    <el-date-picker
                      v-model="props.row.mfg"
                      type="date"
                      class="wid120"
                      :editable="false"
                      value-format="yyyy-MM-dd"
                      :disabled="props.row.dateDisabled"
                      :clearable="false"
                      size="mini"
                      @change="
                        (val) => {
                          fenjiantime(val, props);
                        }
                      "
                    />
                  </template>
                </el-table-column>
                <el-table-column label="库存" prop="inventory_num" width="120" v-if="field == 6">
                  <template slot-scope="props">{{
                    props.row.goods_spu.inventory
                      ? props.row.goods_spu.inventory.num
                      : ""
                  }}</template>
                </el-table-column>
                <el-table-column
                  label="库存单价"
                  prop="inventory_price"
                  width="120"
                  v-if="field == 7"
                >
                  <template slot-scope="props">{{
                    props.row.goods_spu.inventory
                      ? props.row.goods_spu.inventory.price
                      : ""
                  }}</template>
                </el-table-column>
                <el-table-column label="分拣状态" width="100" v-if="field == 8">
                  <template slot-scope="props">
                    <div class="main_link">
                      <el-link type="danger" v-if="props.row.status == 0"
                        >未分拣</el-link
                      >
                      <el-link type="success" v-else>已分拣</el-link>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  width="120"
                  prop="remark"
                  v-if="field == 9"
                />
                <el-table-column
                  label="分拣员"
                  :prop="null"
                  width="120"
                  :show-overflow-tooltip="true"
                  v-if="field == 10"
                >
                  <template slot-scope="scope">
                    {{ sort_user[scope.row.sort_uid] }}
                  </template>
                </el-table-column>
                <el-table-column label="分拣时间" width="120" v-if="field == 11">
                  <template slot-scope="props">
                    {{
                      props.row.sort_time
                        ? parseTime(props.row.sort_time, "{y}-{m}-{d}")
                        : ""
                    }}
                  </template>
                </el-table-column>
              </div>
              <el-table-column
                label="管理操作"
                align="left"
                fixed="right"
                width="200"
                class-name="main_hei"
                label-class-name="main-center"
              >
                <template slot-scope="props">
                  <span
                    slot="reference"
                    v-if="props.row.order_status == 1"
                  >
                    <el-link
                      type="warning"
                      v-if="props.row.status == 0"
                      @click="quehuo(props.row.id, props, boxindex)"
                      >缺货</el-link
                    >
                  </span>

                  <el-link
                    @click="printReceipt(props.row.id)"
                    v-if="props.row.status == 1 || no_sorting_printing"
                    >打印</el-link
                  >
                  <span v-if="props.row.order_status == 1">
                    <el-link
                      type="danger"
                      slot="reference"
                      v-if="props.row.status == 1"
                      @click="chexiaoMethod(props.row.id, props, boxindex)"
                      >撤销</el-link
                    >
                  </span>
                  <el-link
                    @click="accumu(boxindex, props)"
                    v-if="props.row.order_status == 1"
                    >累加</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="tips" v-if="!tableList.length">
          <span class="el-icon-warning-outline"></span>暂无数据
        </div>
      </div>

      <div class="main_num boxdq mg-t-10">
        <div class="main_num_l box">
          <p>
            总分拣用户：
            <em>{{ sort_arr_list.count || 0 }}</em>
          </p>
          <p>
            已分拣完成用户：
            <em>{{ over_count || 0 }}</em>
          </p>
          <p>
            未分拣用户：
            <em>{{ sort_arr_list.up_count || 0 }}</em>
          </p>
          <p>
            部分分拣用户：
            <em>{{ sort_arr_list.in_count || 0 }}</em>
          </p>
          <p class="box" style="width: 400px; align-items: center">
            分拣进度：
            <el-progress
              :text-inside="true"
              :stroke-width="15"
              :percentage="fenjian_percent"
              status="success"
              color="#E47C02"
              style="width: 60%"
            ></el-progress>
          </p>
        </div>
        <!-- 分页 -->
        <div class="main_page_r">
          <MainPagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>

    <el-dialog
      title="表头设置"
      :visible.sync="dialogFormVisible"
      class="main_dialog dialog500"
      @close="type = list.field"
    >
      <div class="set_sort">
        <div class="set_none_show">
          <el-checkbox-group v-model="type">
            <el-checkbox
              v-for="(Header, index) in Header"
              :key="index"
              :label="Header.id"
              :disabled="Header.disabled"
              >{{ Header.name }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
        <div class="set_header_sort">
          <div class="set_sort_ab">
            <draggable chosen-class="chosen" v-model="Header" animation="500">
              <transition-group>
                <li
                  class="set_sort_ab_border"
                  v-for="item in Header"
                  :key="item.id"
                >
                  <div>
                    <span class="el-icon-d-caret"></span>
                    <span>{{ item.name }}</span>
                  </div>
                  <svg-icon icon-class="index_move" />
                </li>
              </transition-group>
            </draggable>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setupmine" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 累加分拣弹出窗 -->
    <el-dialog
      title="累加分拣"
      :visible.sync="addDialogFormVisible"
      width="30%"
    >
      <div class="dialog_padding20_30">
        <el-form :model="form" @submit.native.prevent>
          <el-form-item label="下单数量：" label-width="120px" class="addfenjian">
            <span class="add_num">{{ addInfo.order_num }}</span>
          </el-form-item>
          <el-form-item label="已分拣数量：" label-width="120px" class="addfenjian">
            <span class="add_num">{{ addInfo.sort_num }}</span>
          </el-form-item>
          <el-form-item label="分拣数量：" label-width="120px" class="addfenjian">
            <el-input
              v-model.trim="addInfo.new_num"
              autocomplete="off"
              placeholder="智能称或输入数量后回车"
              size="medium"
              autofocus="true"
              type="number"
              ref="addInfoInput"
              @keyup.enter.native="countadd(1)"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否分次打印：" label-width="120px">
            <el-tooltip
              class="item"
              effect="dark"
              content="勾选后，每次累加数量都会打印标签"
              placement="bottom"
            >
              <i class="el-icon-question icon" style="padding-rigth: 30px"></i>
            </el-tooltip>
            <el-switch
              v-model="isPrint"
              active-text="开"
              inactive-text="关"
              active-color="#03A98E"
              class="mainor_switch"
              style="margin-left: 20px"
            ></el-switch>
          </el-form-item>
          <el-form-item label="累加明细：" label-width="120px">
            <el-tag
              size="mini"
              v-for="(item, index) in addInfo.numhistory"
              style="margin-right: 8px"
              :key="index"
              >{{ item }}</el-tag
            >
          </el-form-item>
          <el-form-item label="本次分拣数量：" label-width="120px" class="addfenjian">
            <span class="add_num">{{ addInfo.add_sum }}</span>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="accountComplete">完 成</el-button>
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打印子组件 -->
    <order-print
      ref="printTemplate"
      v-show="false"
      id="printname"
    ></order-print>

    <!-- 打印小票 -->
    <sort-note-print
      ref="printReceiptTemplate"
      v-show="false"
      id="printReceiptName"
    ></sort-note-print>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import { field_getField } from "@/api/sort";
import {
  sorting_accumulation,
  sorting_stock,
  sorting_revoke,
  sorting_add,
  sorting_add_time,
  sortingUserindex,
  sortingUserOrder,
} from "@/api/sorting/sortingStart";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import { recursion, category, parseTime } from "@/utils/index";
import { field_save, setting_company } from "@/api/currency";
import OrderPrint from "@/views/order/orderPrint.vue";
import SortNotePrint from "@/views/sorting/sortPrintNote.vue";
import { sortingTwoHeader } from "@/options/headerSet";
import { mapGetters } from "vuex";
import draggable from "vuedraggable";
import { user_getMemberInfo } from "@/api/currency";
export default {
  mixins: [mixins],
  components: {
    OrderPrint,
    SortNotePrint,
    draggable,
  },
  data() {
    return {
      borderHeights: 0,
      // 时间
      parseTime,
      // 选中的行inputFocus
      userRow: {
        boxindex: "",
        rowindex: "",
      },
      // 更多
      moredata: false,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 搜索
      form: {
        send_time: parseTime(new Date(), "{y}-{m}-{d}"), //配送日期
        uid: "", //用户名称
        send_time_id: 0, //配送时间
        sortinguser: 0, //分拣状态
        line_id: 0, //用户路线
        group_id: 0, //用户分组
        region_id: 0, //用户区域
        zid: "",
        sort_rule: localStorage.getItem("sort_rule") || "1", // 是否按商品排序
      },
      zid_name: [],
      type: false,
      // 总分拣单元 统计
      sort_arr_list: {
        count: 0, //总的
        down_count: 0,
        in_count: 0, //部分
        up_count: 0,
        over_count: 0, //已完成
        no_count: 0, //没有
      },
      // 分拣员
      sort_user: {},
      // 累加操作的信息
      addInfo: {
        id: "",
        num: "", //原始数据
        numhistory: [], //添加的记录
        new_num: "", //添加数据
        order_num: "", //下单数量
        sort_num: "0", //分拣数量
        add_sum: 0, //本次分拣的和
      },
      // 是否分次打印
      isPrint: false,
      // 累加弹出窗
      addDialogFormVisible: false,
      // 列表数据
      tableList: [],
      searchFormData: {},
      // 用户标签
      labels: {},
      listLoading: true,
      // 表头设置
      dialogFormVisible: false,
      type: [],
      // 表头设置列表
      field: {},
      Header: sortingTwoHeader,
      automatic_printing: false,
      not_display_direct_supply_goods: true,
      no_sorting_printing: false,
      temporary_coding: false, //临时编码
      display_direct_delivery: false, //显示直达
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      // 用户选择按钮
      userCheckList: [],
      // 当前的用户行数
      boxindex: 0,
      // 累加时当前行的数据
      accumulation_row: {},
      lines: {},
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    // 已分拣完成订单
    over_count() {
      return (
        this.sort_arr_list.count -
        this.sort_arr_list.up_count -
        this.sort_arr_list.in_count
      );
    },
    // 分拣经度进度
    fenjian_percent() {
      let percent = 0;
      if (this.sort_arr_list.count == 0) {
        percent = 0;
      } else {
        percent = (this.over_count / this.sort_arr_list.count) * 100;
      }
      percent = Math.round(percent);
      return percent;
    },
    lineType() {
      return function (siteType) {
        return this.lines[siteType];
      };
    },
    isAllSelected() {
      return this.userCheckList.length && this.userCheckList.length == this.tableList.length;
    },
    isItemSelected() {
      // 检查项是否被选择的函数
      return (item) => this.userCheckList.some((selected) => selected.id === item.id);
    },
  },
  created() {
    // 列表
    this.$nextTick(() => {
      this.getNumerical(200);
      this.borderHeights = this.borderHeight;
    });
    this.getList();
  },
  mounted() {
    this.sort_data();
  },
  // 刷新
  inject: ["reload"],
  methods: {
    getSearchFor() {
      this.getArticleList();
    },
    startGetting() {
      this.getArticleList();
    },
    //排序
    sort_data() {
      let data = packApi({ type: 9 });
      field_getField(data).then((res) => {
        let arry = JSON.parse(res.data.info.sort);
        if (arry || arry.length) {
          this.Header.sort((a, b) => {
            return arry.indexOf(a.id) - arry.indexOf(b.id);
          });
        }
      });
    },
    //获取用户信息
    getUser(data) {
      let uid = data.info.user_id;
      this.form.uid = uid;
      this.getList();
    },
    // 清除用户的uid
    clearUid() {
      this.form.uid = "";
      this.form.zid = "";
      this.zid_name = [];
    },
    //展示子账号
    uidName(uid) {
      let data = packApi({
        id: uid,
      });
      user_getMemberInfo(data).then((res) => {
        if (res.errcode == 0) {
          this.form.zid = "";
          this.form.zid_name = null;
          res.data.subAccount.map((e, ind) => {
            if (ind == 0) {
              e.id = 0;
              e.nickname = "主账号";
            }
          });
          res.data.subAccount.unshift({
            id: "",
            nickname: "所有",
          });
          this.zid_name = res.data.subAccount;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    userSelectionChange(val, item) {
      if (val) {
        this.userCheckList.push(item);
      } else {
        var len = this.userCheckList.length;
        var index = 0;
        for (let i = 0; i < len; i++) {
          if (item.id == this.userCheckList[i].id) {
            index = parseInt(i);
          }
        }
        this.userCheckList.splice(index, 1);
      }
    },

    // 搜索勾选
    checkboxChange(val, type) {
      let parmas = {};
      if (type == 1) {
        parmas.automatic_printing = val ? 1 : 0;
        // let parmas = { automatic_printing: val ? 1 : 0 };
      } else if (type == 2) {
        parmas.no_sorting_printing = val ? 1 : 0;
        // let parmas = { no_sorting_printing: val ? 1 : 0 };
      } else if (type == 3) {
        parmas.temporary_coding = val ? 1 : 0;
      } else if (type == 4) {
        parmas.display_direct_delivery = val ? 1 : 0;
      } else if (type == 5) {
        parmas.not_display_direct_supply_goods = val ? 1 : 0;
      }
      let data = packApi(parmas);
      setting_company(data).then((res) => {
        if (res.errcode == 0) {
          if (type == 5) {
            this.getArticleList();
          }
        } else {
        }
      });
    },
    // 修改商品排序
    changeSortRule(val) {
      localStorage.setItem("sort_rule", val);
      this.getList();
    },
    // 单元格的style 的回调方法
    cellStyle({ row, rowIndex }) {
      if (rowIndex === this.userRow.rowindex) {
        return "success";
      } else {
        return;
      }
    },

    // input 框聚焦时
    inputFocus(boxindex, scope, $event) {
      this.userRow.boxindex = boxindex;
      this.userRow.rowindex = scope.$index;
      scope.row.sort_num = "";
    },
    // 失去焦点
    inputBlur(boxindex, scope, $event) {
      this.userRow.rowindex = -1;
    },
    // 焦点离开商品分类
    nextFocus(boxindex, scope, $event, status) {
      let id = scope.row.id;
      let index = scope.$index;
      let val = $event.target.value;
      let newindex = index + 1;
      if (/^(\d+\.?)?\d{0,2}$/.test(parseFloat(val)) && val != "") {
        $event.target.blur();
        let parmas = {
          id: id,
          num: val,
          status,
        };
        if (val == 0) {
          scope.row.out_status = 1;
        }
        scope.row.disabled = true;
        scope.row.status = 1;
        this.xiugai(parmas).then((res) => {
          if (res.errcode == 40202) {
            this.$confirm(res.errmsg + "，是否保存？", "提示", {
              type: "warning",
            })
              .then(() => {
                this.nextFocus(boxindex, scope, $event, 1);
              })
              .catch(() => {
                scope.row.disabled = false;
                scope.row.status = 0;
                this.$nextTick(() => {
                  this.$refs["sorting" + boxindex + index][0].focus();
                });
              });
          }

          if (res.errcode == 0 && this.automatic_printing) {
            this.printReceipt(scope.row.id);
          }
        });
        if (this.$refs["sorting" + boxindex + newindex]) {
          this.$refs["sorting" + boxindex + newindex][0].focus();
        } else {
          if (boxindex + 1 < this.totalCount) {
            boxindex += 1;
            newindex = 0;
            this.$refs["sorting" + boxindex + newindex][0].focus();
          }
        }
      } else {
        this.$message.warning("请输入正确的数字订单");
        $event.target.value = "";
      }
    },
    // 订购数量？注释
    renderHeader(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h("div", [
        // h即为cerateElement的简写
        // 在div里面插入span
        h("span", {
          // 表示内容
          domProps: {
            innerHTML: column.label,
          },
          on: {
            click: () => {
              console.log(`${column.label}   ${$index}`);
            },
          },
        }),
        h(
          "el-tooltip",
          {
            // 表示属性
            attrs: {
              effect: "dark",
              content: "所有档口下单数量的总和！",
              placement: "top",
            },
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg",
            }),
          ]
        ),
      ]);
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.getList();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.form.uid = "";
      this.$refs["changeUserInput"].name = "";
      this.createTime = [];
      this.establishTime = [];
      this.getArticleList();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.getList();
    },
    changePage(page) {
      this.current.page = page;
      this.getList();
    },
    // 设置确认
    setupmine(val) {
      let arry = [];
      let arrys = [];
      this.Header.map((e) => {
        arrys.push(e.id);
        this.type.map((p) => {
          if (e.id == p) {
            arry.push(e.id);
            return;
          }
        });
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { type: 9 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { type: 9, fields: JSON.stringify(arry), sort: JSON.stringify(arrys) }
      );
      field_save(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "设置成功",
            type: "success",
          });
          // this.reload();
          this.getList();
        } else {
          this.$message.error(res.errmsg);
        }
      });
      this.dialogFormVisible = false;
    },
    // 展开/收起
    expandChange(index) {
      let row = this.tableList[index];
      row.is_expand = !row.is_expand;
      if(!row.list.length && !row.loading) this.getChildrenList(row);
    },
    getChildrenList(row) {
      row.loading = true;
      if(row.list.length && row.loading) return;
      let data = packApi({
        uid: row.uid,
        uid_zid: row.uid_zid,
        send_time: this.form.send_time,
      });
      sortingUserOrder(data).then(res=> {
        row.loading = false;
        if(res.errcode == 0) {
          row.list = res.data.map(item=> {
            if(item.status == 0) {
              item.sort_num = "";
            }
            if (item.order_status != 1) {
              item.disabled = true;
              item.dateDisabled = true;
            } else {
              item.disabled = item.status == 0 ? false : true;
              item.dateDisabled = false;
            }
            return item;
          });
        }else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 列表
    getList() {
      this.listLoading = true;
      let data = packApi({
        ...this.form,
        ...this.current,
      });
      sortingUserindex(data).then(res=> {
        this.listLoading = false;
        if(res.errcode == 0) {
          this.labels = res.data.labels;
          this.lines = res.data.line;
          this.sort_arr_list = res.data.sort_arr_list;
          this.tableList = res.data.list.map(e => {
            e.is_expand = false;
            e.loading = false;
            e.list = [];
            // 筛选--开始
            let labels_ids = this.labels ? Object.keys(this.labels) : [];
            e.labels = labels_ids.filter((item) => e.labels.includes(item));
            // 结束
            return e;
          });
          this.automatic_printing = res.data.automatic_printing == 1;
          this.not_display_direct_supply_goods = res.data.not_display_direct_supply_goods == 1;
          this.no_sorting_printing = res.data.no_sorting_printing == 1;
          this.temporary_coding = res.data.temporary_coding == 1;
          this.display_direct_delivery = res.data.display_direct_delivery;
          this.field = res.data.field;
          this.type = res.data.field;
          this.sort_user = res.data.sort_user;
          this.totalCount = res.data.page.count;
          this.searchFormData = res.data;
          if(!this.tableList.length) return;
          this.$nextTick(()=> {
            this.tableList[0].is_expand = !this.tableList[0].is_expand;
            this.getChildrenList(this.tableList[0]);
          })
        } else {
          this.$message.error(res.errmsg);
        }
      })
    },
    // 商品累计添加
    sorting_accumulation(val) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name) + apiUrl().appsecret)
          ),
        },
        { id: this.addInfo.id, num: val }
      );
      return new Promise((resolve, reject) => {
        sorting_accumulation(data).then((res) => {
          if (res.errcode !== 0) {
            reject();
            this.$message.error("添加失败，请重试");
          } else {
            resolve();
          }
        });
      });
    },
    // 分拣缺货
    quehuo(id, props, boxindex) {
      this.$confirm("您确定对该商品进行缺货备注吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name) + apiUrl().appsecret)
              ),
            },
            { id: id }
          );

          let row = props.row;
          let index = props.$index;
          let newindex = index + 1;
          sorting_stock(data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success("提交成功");
              row.out_status = 1;
              row.status = 1;
              row.sort_time = new Date();
              row.sort_num = 0;
              row.sort_uid = this.userInfo.id;
              if (row.order_status != 1) {
                row.disabled = true;
                row.dateDisabled = true;
              } else {
                row.disabled = row.status == 0 ? false : true;
                row.dateDisabled = false;
              }

              if (this.$refs["sorting" + boxindex + newindex]) {
                this.$refs["sorting" + boxindex + newindex][0].focus();
              } else {
                if (boxindex + 1 < this.totalCount) {
                  boxindex += 1;
                  newindex = 0;
                  this.$refs["sorting" + boxindex + newindex][0].focus();
                }
              }
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 分拣撤销
    chexiao(id, props, boxindex) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name) + apiUrl().appsecret)
          ),
        },
        { id: id }
      );

      let row = props.row;
      let status = row.status;
      let out_status = row.out_status;
      let index = props.$index;
      let newindex = index + 1;
      sorting_revoke(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("商品撤销成功");
          row.modify = 0;
          row.out_status = 0;
          row.sort_uid = 0;
          row.sort_time = 0;
          row.status = 0;
          row.sort_num = 0;
          row.mfg = "";
          row.inventory_price = "";
          if (row.status == 0) {
            if (row.sort_num == 0.0 || row.sort_num) {
              row.sort_num = "";
            }
          }
          if (row.order.order_status != 1) {
            row.disabled = true;
            row.dateDisabled = true;
          } else {
            row.disabled = row.status == 0 ? false : true;
            row.dateDisabled = false;
          }
          this.$nextTick(() => {
            if (this.$refs["sorting" + boxindex + index]) {
              this.$refs["sorting" + boxindex + index][0].focus();
            } else {
              if (boxindex + 1 < this.totalCount) {
                boxindex += 1;
                index = 0;
                this.$refs["sorting" + boxindex + index][0].focus();
              }
            }
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    chexiaoMethod(id, props, boxindex) {
      this.$confirm("将撤销该分拣商品, 是否确定?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.chexiao(id, props, boxindex);
        })
        .catch(() => {});
    },
    // 累加框展示
    accumu(boxindex, value) {
      this.boxindex = boxindex;
      let res = value.row;
      this.accumulation_row = value;
      this.addInfo.id = res.id;
      this.addInfo.num = res.sort_num;
      this.addInfo.order_num = res.order_num;
      this.addInfo.sum = 0;
      this.addInfo.sort_num = 0;
      this.addInfo.add_sum = 0;
      if (res.sort_num) {
        this.addInfo.sort_num = res.sort_num;
      }
      this.addInfo.numhistory = [];
      this.addDialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["addInfoInput"].focus();
      });
    },
    // 累加回车事件
    countadd(value) {
      if (this.addInfo.new_num == "") {
        return;
      }
      this.addInfo.num =
        parseFloat(this.addInfo.num) + parseFloat(this.addInfo.new_num);
      this.addInfo.numhistory.push(this.addInfo.new_num);
      if (this.isPrint) {
        this.printReceipt(this.addInfo.id, this.addInfo.new_num);
      }
      if (this.addInfo.new_num) {
        this.addInfo.add_sum += parseFloat(this.addInfo.new_num);
      }
      this.addInfo.new_num = "";
    },
    // 累加完成事件
    accountComplete() {
      if (this.addInfo.add_sum) {
        let scope = this.accumulation_row;
        let index = scope.$index;
        let boxindex = this.boxindex;
        let newindex = index + 1;
        scope.row.disabled = true;
        scope.row.status = 1;
        let sort_num = 0;
        if (scope.row.sort_num) {
          sort_num = scope.row.sort_num;
        }
        scope.row.sort_num =
          parseFloat(sort_num) + parseFloat(this.addInfo.add_sum);
        this.$nextTick(() => {
          this.addDialogFormVisible = false;
          if (this.$refs["sorting" + boxindex + newindex]) {
            this.$refs["sorting" + boxindex + newindex][0].focus();
          } else {
            if (boxindex + 1 < this.totalCount) {
              boxindex += 1;
              newindex = 0;
              this.$refs["sorting" + boxindex + newindex][0].focus();
            }
          }
        });
        this.sorting_accumulation(this.addInfo.add_sum)
          .then(() => {})
          .catch(() => {
            this.getList();
          });
      }
    },
    // 分拣修改请求
    xiugai(parmas) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name) + apiUrl().appsecret)
          ),
        },
        parmas
      );
      return new Promise((resolve, reject) => {
        sorting_add(data).then((res) => {
          resolve(res);
        });
      });
    },
    // 生产日期修改
    fenjiantime(val, scope) {
      let id = scope.row.id;
      let params = {
        id: id,
        mfg: val,
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name) + apiUrl().appsecret)
          ),
        },
        params
      );
      sorting_add_time(data).then((res) => {});
    },
    // 分拣修改事件
    xiugaiMethod(scope) {
      scope.row.disabled = !scope.row.disabled;
    },

    //打印
    print(item) {
      let oid = item.oid;
      this.$refs.printTemplate.$emit("demo", {
        id: oid,
        type: "sortuser",
        sort_rule: this.form.sort_rule,
      });
    },
    // 全选
    selectAll() {
      this.userCheckList = this.isAllSelected ? [] : this._.cloneDeep(this.tableList);
    },
    //批量打印
    batchprint() {
      if (!this.userCheckList.length) throw this.$message.error("请勾选订单");
      this.$confirm(
        `此操作将连续打印【${this.userCheckList.length}】张拣货单,并且打印机需要设置为后进纸,是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          for (let i = 0; i < this.userCheckList.length; i++) {
            let oid = this.userCheckList[i].oid;
            this.$refs.printTemplate.$emit("demo", {
              id: oid,
              type: "sortuser",
              sort_rule: this.form.sort_rule,
            });
          }
        })
        .catch(() => {});
    },
    // 打印小票
    printReceipt(id, num) {
      this.printid = id;
      // this.$refs.printReceiptTemplate.$emit("sortPrintNote", {
      //   id: id,
      //   num: num,
      // });
      return new Promise((resolve, reject) => {
        this.$refs.printReceiptTemplate.$emit("sortPrintNote", {
          data: {
            id: id,
            num: num,
          },
          cb: (res) => {
            resolve(res);
          },
        });
      });
    },
    // 打印全部件货单
    printAll() {
      let length = "";
      let arr = [];
      if (this.userCheckList.length) {
        length = this.userCheckList.length;
        arr = this.userCheckList;
      } else {
        arr = this.tableList;
        length = this.tableList.length;
      }
      this.$confirm(`系统将连续打印${length}个商品，确定吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          arr.forEach((item) => {
            setTimeout(() => {
              this.print(item);
            }, 300);
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainor_form form {
  width: 100%;
  .mainsw_fo {
    margin-bottom: 3px;
    display: flex;
    /deep/.el-select {
      margin-bottom: 15px;
    }
    /deep/.el-cascader {
      margin-bottom: 15px;
    }
  }
}
.batch-wrap-right {
  display: flex;
  .el-checkbox {
    flex: 15%;
    margin-right: 12px;
  }
}
/deep/.main_table .el-table--small .cell {
  height: 30px !important;
  line-height: 30px;
}
.mainsa_te {
  svg {
    vertical-align: -2px;
  }
  use {
    fill: #c1c1c1;
  }
}
.mainsw_ta {
  /deep/.el-checkbox-group {
    font-size: initial;
  }
  .mainsw_tax {
    margin-top: 20px;
    &:first-child {
      margin-top: 0;
    }
    .mainsw_tax_t {
      margin-bottom: 2px;
      overflow-x: auto;
      /deep/.el-button {
        position: absolute;
        right: 35px;
        margin-top: 8px;
      }
      table {
        width: 100%;
        border-collapse: collapse;
        table-layout: fixed;
        word-break: break-all;
        border-spacing: 0;
        thead {
          height: 51px;
          line-height: 51px;
          background: $colour_f7;
          th {
            font-size: $font_14;
            color: $colour_3;
            text-align: left;
            padding-left: 10px;
            padding-right: 10px;
          }
        }
        .mainsw_tax_tb {
          height: 2px;
        }
        tbody {
          tr {
            background: $colour_f7;
            td {
              word-break: break-all;
              height: 51px;
              line-height: 51px;
              font-size: $font_14;
              color: $colour_3;
              padding-left: 10px;
              padding-right: 10px;
              .mainsw_tax_th {
                height: 20px;
                line-height: 20px;
              }
              .mainsw_tax_ts {
                margin-left: 20px;
              }
            }
          }
        }
      }
      /deep/.el-checkbox__label {
        display: none;
      }
    }
  }
}

/deep/.el-table tr.expanded + tr .mainex_ta {
  background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr .mainex_ta th,
/deep/.el-table tr.expanded + tr .mainex_ta tr {
  background: #fafafa !important;
}

// 当表格行选择的时候
/deep/.el-table .success {
  color: red;
  font-weight: 700;
  font-size: 20px;
}
.table {
  width: 100%;
  // height: 200px;
  min-height: 150px;
  .table-item {
  }
  .tips {
    height: 100%;
    text-align: center;
    padding-top: 50px;
    box-sizing: border-box;
  }
}

// 分拣弹出窗
.addfenjian {
  /deep/ .el-input__inner {
    padding-right: 0 !important;
  }
  .add_num {
    font-size: 16px;
  }
}

// 当表格行选择的时候
.el-table .success {
  color: red;
  font-weight: 700;
  font-size: 20px;
}
.new_navbar_svg {
  vertical-align: top;
  use {
    fill: #c1c1c1;
  }
}

.user-label {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.item-label {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.item-label span {
  height: auto;
  padding: 4px 10px;
  border: 1px solid #e6a23c;
  color: #e6a23c;
  margin-bottom: 5px;
  border-radius: 3px;
  margin-right: 10px;
}

.label-pic {
  width: 17px;
  height: 20px;

  .header_setting {
    margin-left: 15px;
    transform: translateY(2px);
    use {
      fill: #606266;
    }
  }
}
/deep/.el-input.is-disabled .el-input__inner {
  color: #666;
}
/deep/.el-dialog__body {
  padding: 0;
}
/deep/.el-checkbox {
  flex: 30%;
}
/deep/.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}

/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px !important;
}
.boxd {
  position: absolute;
  top: 47px;
  right: 0;
}

.expand-box {
  position: relative;
  i {
    font-size: 18px;
    font-weight: bold;
    margin-right: 5px;
  }

}
/deep/.el-table__empty-block {
  min-height: 0;
}
</style>
